package com.hbr.activity;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.Calendar;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import com.hbr.R;

public class FightQueryActivity extends Activity implements OnClickListener {
    private EditText etStartCity;
    private EditText etLastCity;
    private DatePicker dpTheDate;
    private Button btnSearch;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.flightsearch);
        etStartCity = (EditText) findViewById(R.id.etStartCity);
        etLastCity = (EditText) findViewById(R.id.etLastCity);
        dpTheDate = (DatePicker) findViewById(R.id.dpTheDate);
        btnSearch = (Button) findViewById(R.id.btnSearch);
        etStartCity.setText("青岛");
        etLastCity.setText("北京");
        Calendar ca = Calendar.getInstance();
        dpTheDate.updateDate(ca.get(Calendar.YEAR), ca.get(Calendar.MONTH), ca.get(Calendar.DAY_OF_MONTH));

        btnSearch.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (v == btnSearch) {
            if (TextUtils.isEmpty(etStartCity.getText().toString())) {
                Toast.makeText(this, R.string.emptyStart, Toast.LENGTH_SHORT).show();
            } else if (TextUtils.isEmpty(etLastCity.getText().toString())) {
                Toast.makeText(this, R.string.emptyLast, Toast.LENGTH_SHORT).show();
            } else {
                int iYear = dpTheDate.getYear();
                int iMonth = dpTheDate.getMonth();
                int iDay = dpTheDate.getDayOfMonth();
                Calendar c = Calendar.getInstance();
                c.set(iYear, iMonth, iDay);
                Calendar c1 = Calendar.getInstance();
                if (c.compareTo(c1) < 0) {
                    Toast.makeText(this, R.string.dateBefore, Toast.LENGTH_SHORT).show();
                } else {
                    new SearchDate().execute("");
                }
            }
        }
    }

    private void send(String result) {
        if (TextUtils.isEmpty(result)) {
            Toast.makeText(this, R.string.getError, Toast.LENGTH_SHORT).show();
        } else {
            startActivity(new Intent(this, ResultActivity.class).putExtra("result", result));
        }
    }

    class SearchDate extends AsyncTask<String, Integer, String> {
        private ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            pd = new ProgressDialog(FightQueryActivity.this);
            pd.setMessage("Searching ……");
            pd.show();
        }

        @Override
        protected String doInBackground(String... params) {
            // searching
            String strUrl = "http://www.webxml.com.cn/webservices/DomesticAirline.asmx/getDomesticAirlinesTime?startCity="
                    + etStartCity.getText().toString()
                    + "&lastCity="
                    + etLastCity.getText().toString()
                    + "&theDate="
                    + dpTheDate.getYear()
                    + "-"
                    + (dpTheDate.getMonth() + 1)
                    + "-"
                    + dpTheDate.getDayOfMonth()
                    + "&userID=";
            String result = "";
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet pageGet = new HttpGet(strUrl);
                HttpResponse response = httpClient.execute(pageGet);
                InputStream sis = response.getEntity().getContent();
                BufferedInputStream bis = new BufferedInputStream(sis);
                ByteArrayBuffer bab = new ByteArrayBuffer(32);
                int current = 0;
                while ((current = bis.read()) != -1) {
                    bab.append((byte) current);
                }
                result = EncodingUtils.getString(bab.toByteArray(), HTTP.UTF_8);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            send(result);
            pd.dismiss();
        }

    }

}